#!/usr/bin/env python3

import shelve
import sys
import os
import re
from github_social_network_graph import GH_User

FIELDS = ['login',
          'name',
          'email',
          'location',
          'id',
          'type',
          'created_at',
          'sequence_number',
          'followers_number',
          'following_number']

def continue_yesno():
    while 1:
        ans = input('continue? [Y/n] ')
        if ans == 'y' or ans == '':
            return 1
        elif ans == 'n':
            return 0
        else:
            print('response "{0}" not understood'.format(ans))

def escape_meta_symbols(string, metasyms, esc):
    i = 0
    ret = ''
    while i < len(string):
        if string[i] in metasyms:
            ret += esc
        ret += string[i]
        i += 1
    return ret

def check_access(filename, perm):
    if not os.access(filename, perm):
        print('could not open file "{}" for reading'.format(filename), file=sys.stderr)
        sys.exit(1)
    else:
        return 0

def filter_unprintable(s):
    f = filter(lambda x: x.isalnum() or x.isprintable() or (x in '\t\n'), s)
    return ''.join(f)

def main():
    check_access(sys.argv[1], os.R_OK)
    sh = shelve.open(sys.argv[1], 'r')
    pool = sh['pool']
    sh.close()
    del sh

    roster = [x for x in pool.keys()]
    roster.sort()

    for login in roster:
        person = pool[login]
        parameters_l = []
        for parameter in person.Allowed_fields:
            parameter_arg_s = ''
            parameter_arg = getattr(person, parameter, None)
            if type(parameter_arg) == type(str()):
                if parameter_arg == 'None':
                    parameter_arg = 'nil'
                parameter_arg_s = '"{}"'.format(escape_meta_symbols(filter_unprintable(parameter_arg), ['\n', '\\', '\'', '\"'], '\\'))
            elif type(parameter_arg) == type(bool()):
                parameter_arg_s = 'true' if parameter_arg == True else 'false'
            elif type(parameter_arg) == type(list()):
                parameter_arg_s = '{'
                parameter_arg = ['"{0}"'.format(x) for x in parameter_arg]
                parameter_arg_s += ', '.join(parameter_arg) + '}'
            else:
                parameter_arg_s = str(getattr(person, parameter, 'nil'))
            parameters_l.append('["{0}"] = {1}'.format(str(parameter), parameter_arg_s))
        parameters_s = ", ".join(parameters_l)
        sys.stdout.write('GHUser{' + parameters_s + '}\n')
    sys.stdout.flush()

if __name__ == '__main__':
    main()
